<template>
  <div class="lawcase-container">
    <el-card class="lawcase-header">
      <template #header>
        <div class="card-header">
          <h3>案件管理列表</h3>
          <div class="header-actions">
            <el-button
              type="primary"
              :icon="isSearchExpanded ? 'ArrowUp' : 'ArrowDown'"
              @click="toggleSearchExpanded"
              class="toggle-search-btn"
            >
              {{ isSearchExpanded ? '收起搜索' : '展开搜索' }}
            </el-button>
            <el-button type="success" @click="handleAdd">+ 新增案件</el-button>
          </div>
        </div>
      </template>

      <div v-if="isSearchExpanded" class="search-container">
        <el-form
          :model="queryForm"
          ref="queryFormRef"
          :inline="true"
          label-width="auto"
          class="search-form"
        >
          <el-form-item label="关键词" prop="keywords">
            <el-input
              v-model="queryForm.keywords"
              placeholder="案件编号/委托人"
              clearable
              @keyup.enter="handleSearch"
              class="search-input"
            />
          </el-form-item>
          <el-form-item label="主办律师" prop="main_lawyer">
            <el-select
              v-model="queryForm.main_lawyer"
              placeholder="请选择主办律师"
              clearable
              filterable
              class="search-select"
            >
              <el-option
                v-for="lawyer in lawyerOptions"
                :key="lawyer.lawyer_id || 'default-key'"
                :label="lawyer.lawyer_name || ''"
                :value="lawyer.lawyer_id || ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="管家" prop="manager">
            <el-select
              v-model="queryForm.manager"
              placeholder="请选择管家"
              clearable
              filterable
              remote
              :remote-method="remoteSearchManagers"
              :loading="managerLoading"
              class="search-select"
            >
              <el-option
                v-for="option in managerOptions"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="出庭律师" prop="session_lawyer">
            <el-select
              v-model="queryForm.session_lawyer"
              placeholder="请选择出庭律师"
              clearable
              filterable
              class="search-select"
            >
              <el-option
                v-for="lawyer in lawyerOptions"
                :key="lawyer.lawyer_id || 'default-key'"
                :label="lawyer.lawyer_name || ''"
                :value="lawyer.lawyer_id || ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="当前进度" prop="status">
            <el-select
              v-model="queryForm.status"
              placeholder="请选择当前进度"
              clearable
              class="search-select"
            >
              <el-option
                v-for="(status, index) in CASE_STATUS"
                :key="index"
                :label="status"
                :value="status || ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="挂起状态" prop="suspend_status">
            <el-select
              v-model="queryForm.suspend_status"
              placeholder="全部"
              clearable
              class="search-select"
            >
              <el-option label="挂起" :value="1" />
              <el-option label="正常" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="接案日期" prop="date_range">
            <el-date-picker
              v-model="queryForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item label="开庭日期" prop="session_time_range">
            <el-date-picker
              v-model="queryForm.session_time_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="lawcase-content">
      <el-table
        :data="caseList"
        border
        :loading="loading"
        style="width: 100%"
        :cell-style="cellStyle"
        height="calc(100vh - 330px)"
        class="lawcase-table"
      >
        <el-table-column label="进度" width="80" align="center" fixed="left">
          <template #default="{ row }">
            <el-tooltip :content="getProgressGroup(row.status).description" placement="top">
              <el-icon
                :style="{ color: getProgressGroup(row.status).color, fontSize: '20px' }"
                :class="'progress-icon-' + getProgressGroup(row.status).group"
              >
                <component :is="getProgressGroup(row.status).icon" />
              </el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="挂起" width="80" align="center" fixed="left">
          <template #default="{ row }">
            <el-tooltip :content="row.is_suspended === 1 ? '已挂起' : '正常'" placement="top">
              <el-icon
                :style="{ fontSize: '20px', color: row.is_suspended === 1 ? '#f56c6c' : '#67c23a' }"
              >
                <component :is="row.is_suspended === 1 ? 'WarningFilled' : 'CircleCheckFilled'" />
              </el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="case_code" label="案件编号" width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="当前进度" width="200" show-overflow-tooltip />
        <el-table-column label="委托人" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="cell-ellipsis">
              {{ row.clients || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="对方当事人" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="cell-ellipsis">
              {{ row.opponents || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="main_lawyer_name"
          label="主办律师"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="secondary_lawyer_name"
          label="管家"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="session_lawyer_name"
          label="出庭律师"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column label="开庭日期" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.session_time ? formatTime(row.session_time, 'date') : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="contract_id" label="合同ID" width="100" show-overflow-tooltip />
        <el-table-column prop="entrust_date" label="接案日期" width="120" show-overflow-tooltip />
        <el-table-column prop="stage" label="代理阶段" width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-dropdown size="small">
              <el-button type="default" size="small">
                更多
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                  <el-dropdown-item
                    @click="handleSuspend(row)"
                    :style="row.is_suspended === 1 ? 'color: #67c23a;' : ''"
                  >
                    {{ row.is_suspended === 1 ? '取消挂起' : '挂起' }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(row)" style="color: #f56c6c">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑案件抽屉 -->

    <GlobalDrawer
      v-model="addDrawerVisible"
      :title="isEdit ? '编辑案件' : '新增案件'"
      size="80%"
      :before-close="handleAddDrawerClose"
      @confirm="handleSave"
    >
      <CaseEditForm
        ref="caseEditFormRef"
        :visible="addDrawerVisible"
        :is-edit="isEdit"
        :case-data="currentEditCase"
        @update:visible="
          visible => {
            addDrawerVisible = visible
          }
        "
        @success="handleCaseFormSuccess"
      />
    </GlobalDrawer>

    <!-- 查看案件详情抽屉 -->
    <GlobalDrawer v-model="drawerVisible" title="案件详情" size="80%" :show-footer-buttons="false">
      <template #default>
        <div v-if="currentCase">
          <CaseDetailDrawer
            :case-data="currentCase"
            :party-list="partyList"
            :lawyer-list="lawyerOptions as any"
            :progress-list="progressList"
            :format-time="formatTime"
            @add-party="handleAddParty"
            @edit-party="handleEditParty"
            @remove-party="handleRemoveParty"
            @add-progress="handleAddProgress"
            @edit-case="handleEditCase"
            @refresh-case="handleRefreshCase"
          />
        </div>
      </template>
    </GlobalDrawer>

    <!-- 当事人选择器对话框 -->
    <OptimizedPartySelector
      v-model="partySelectorVisible"
      :case-id="currentCase?.id || undefined"
      :contract-id="currentCase?.contract_id || undefined"
      :contract-info="contractInfo || undefined"
      :contact-list="contractContacts || []"
      @success="handlePartySuccess"
    />

    <!-- 当事人编辑对话框 -->
    <PartyAddDialog
      v-model="partyDialogVisible"
      :case-id="currentCase?.id"
      :is-edit="isEditParty"
      :form-data="editPartyForm"
      @success="handlePartyFormSuccess"
      @close="handlePartyDialogClose"
    />

    <!-- 添加进度对话框 -->
    <el-dialog v-model="progressDialogVisible" title="添加案件进度" width="600px">
      <ProgressForm
        ref="progressFormComponentRef"
        :case-id="currentCase?.id"
        @success="handleProgressSuccess"
        @cancel="progressDialogVisible = false"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="progressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitProgress">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { GlobalDrawer } from '@/components/common'
  import { ArrowDown } from '@element-plus/icons-vue'
  import CaseDetailDrawer from './components/CaseDetailDrawer.vue'
  import OptimizedPartySelector from './components/OptimizedPartySelector.vue'
  import CaseEditForm from './components/CaseEditForm.vue'
  import ProgressForm from './components/ProgressForm.vue'
  import PartyAddDialog from './components/PartyAddDialog.vue'
  import { useLawcaseStore } from '@/store/lawcase'
  import { getStageText, getProgressGroup } from '@/constants/lawcase'
  import type { Party, Progress, LawCase } from '@/types'
  import type { CaseLawyer } from '@/types/lawcase'
  import request from '@/utils/request'
  import { formatDate } from '@/utils/format'

  // 规范化时间戳格式 - 确保在被调用前声明
  const normalizeTimestamp = (time: string | number): number => {
    // 确保处理各种时间格式
    if (typeof time === 'string') {
      // 如果是纯数字字符串，尝试转换为数字
      if (/^\d+$/.test(time)) {
        const num = parseInt(time, 10)
        // 检查是否是秒级时间戳（10位左右）
        if (num >= 1000000000 && num < 100000000000) {
          return num * 1000 // 转换为毫秒级时间戳
        }
        return num // 返回原数字
      }
      // 如果是日期字符串，转换为时间戳
      const dateTime = new Date(time).getTime()
      return isNaN(dateTime) ? Date.now() : dateTime
    } else if (typeof time === 'number') {
      // 检查是否是秒级时间戳
      if (time >= 1000000000 && time < 100000000000) {
        return time * 1000 // 转换为毫秒级时间戳
      }
      return time
    }
    // 如果无法处理，返回当前时间戳
    return Date.now()
  }

  // 使用案件store
  const lawcaseStore = useLawcaseStore()

  // 定义转换后的当事人类型
  interface ConvertedParty extends Party {
    id: number
    name: string
    type: 'plaintiff' | 'defendant' | 'other'
    party_name: string
    party_type: number
    [key: string]: any
  }

  // 案件状态常量
  const CASE_STATUS = [
    '准备阶段（未提交立案）',
    '起诉阶段（提交立案待受理）',
    '庭前阶段（立案受理未开庭）',
    '审判阶段（已开庭未出判决）',
    '庭后阶段（已判决未生效）',
    '执行阶段（判决生效）',
    '结案',
    '撤诉',
    '终止委托',
  ]

  // 案件列表查询表单
  const queryForm = reactive({
    page: 1,
    limit: 20,
    keywords: '',
    main_lawyer: '',
    manager: null as number | null | string,
    session_lawyer: '',
    status: '',
    date_range: [],
    session_time_range: [],
    suspend_status: '',
  })

  // 案件列表数据
  const caseList = ref<LawCase[]>([])
  const loading = ref(false)
  const total = ref(0)
  const addDrawerVisible = ref(false)
  const isEdit = ref(false)
  const drawerVisible = ref(false)
  const currentCase = ref<LawCase | null>(null)
  const currentEditCase = ref<LawCase | null>(null)
  const partySelectorVisible = ref(false)
  const progressDialogVisible = ref(false)
  const partyDialogVisible = ref(false)
  const editPartyForm = ref<any>(null)
  const isEditParty = ref(false)

  // 搜索栏展开状态
  const isSearchExpanded = ref(false)

  // 切换搜索栏展开/收缩状态
  const toggleSearchExpanded = () => {
    isSearchExpanded.value = !isSearchExpanded.value
  }

  // 表单引用
  const queryFormRef = ref<FormInstance>()
  const caseFormRef = ref<FormInstance>()
  // 已移除未使用的变量

  // 定义合同和联系人接口（用于当事人选择器）
  interface CaseContractInfo {
    id: number
    code: string
    name: string
    customer_id: number
    customer: string
    [key: string]: any
  }

  interface CaseCustomerContact {
    id: number
    name: string
    phone: string
    mobile: string
    email?: string
    position?: string
  }

  // 律师选项
  const lawyerOptions = ref<CaseLawyer[]>([])
  const managerOptions = ref<any[]>([])
  const managerLoading = ref(false)

  // 子表数据
  const partyList = ref<ConvertedParty[]>([])
  const progressList = ref<Progress[]>([])

  // 合同信息和联系人列表（用于传递给OptimizedPartySelector组件）
  const contractInfo = ref<CaseContractInfo | null>(null)
  const contractContacts = ref<CaseCustomerContact[]>([])

  // 获取案件列表
  const getCaseList = async () => {
    loading.value = true
    try {
      // 转换日期格式，确保传递给后端的日期格式正确
      const startDate = queryForm.date_range?.[0] || ''
      const endDate = queryForm.date_range?.[1] || ''
      // 为开庭日期范围添加适当的格式处理，确保日期字符串格式正确
      const sessionTimeStart = queryForm.session_time_range?.[0]
        ? new Date(queryForm.session_time_range[0]).toISOString().split('T')[0]
        : ''
      const sessionTimeEnd = queryForm.session_time_range?.[1]
        ? new Date(queryForm.session_time_range[1]).toISOString().split('T')[0]
        : ''

      // 确保manager参数格式正确，转换为数字类型
      const managerValue = queryForm.manager
        ? typeof queryForm.manager === 'string'
          ? parseInt(queryForm.manager)
          : queryForm.manager
        : ''

      // 定义params对象的类型
      interface CaseListParams {
        page: number
        limit: number
        keywords: string
        main_lawyer: string
        manager: string | number
        session_lawyer: string
        status: string
        start_date: string
        end_date: string
        session_time_start: string
        session_time_end: string
        secondary_lawyer?: string | number
        is_suspended?: number
      }

      const params: CaseListParams = {
        page: queryForm.page,
        limit: queryForm.limit,
        keywords: queryForm.keywords,
        main_lawyer: queryForm.main_lawyer,
        manager: managerValue,
        session_lawyer: queryForm.session_lawyer,
        status: queryForm.status,
        start_date: startDate,
        end_date: endDate,
        session_time_start: sessionTimeStart,
        session_time_end: sessionTimeEnd,
      }

      // 添加挂起状态参数
      if (
        queryForm.suspend_status !== undefined &&
        queryForm.suspend_status !== null &&
        queryForm.suspend_status !== ''
      ) {
        params.is_suspended = Number(queryForm.suspend_status)
      }

      // 只有当managerValue有值时，才添加secondary_lawyer参数
      if (managerValue) {
        params.secondary_lawyer = managerValue
      }

      const response: any = await request({
        url: '/api/lawcase/cases/list',
        method: 'get',
        params,
      })

      if (response.code === 0) {
        caseList.value = response.data.list
        total.value = response.data.total
      } else {
        ElMessage.error(response.msg || '获取案件列表失败')
      }
    } catch (error) {
      console.error('获取案件列表失败:', error)
      ElMessage.error('获取案件列表失败')
    } finally {
      loading.value = false
    }
  }

  // 远程搜索管家
  const remoteSearchManagers = async (query: string) => {
    if (query.trim() === '') {
      managerOptions.value = []
      return
    }

    managerLoading.value = true

    try {
      const response: any = await request({
        url: '/api/user/user/search',
        method: 'get',
        params: { keyword: query.trim() },
      })

      if (response && response.code === 0) {
        managerOptions.value = response.data || []
      } else {
        managerOptions.value = []
        console.error('搜索管家失败:', response?.msg)
      }
    } catch (error) {
      managerOptions.value = []
      console.error('搜索管家失败:', error)
    } finally {
      managerLoading.value = false
    }
  }

  // 获取律师列表
  const getLawyerList = async () => {
    try {
      const response: any = await request({
        url: '/api/lawcase/cases/get_all_lawyers',
        method: 'get',
        params: {
          limit: 1000, // 设置一个足够大的数值，确保获取所有律师
        },
      })

      if (response.code === 0) {
        // 直接使用后端返回的数据，因为已经是lawyer_id和lawyer_name的格式
        lawyerOptions.value = response.data || []
      } else {
        ElMessage.error(response.msg || '获取律师列表失败')
      }
    } catch (error) {
      console.error('获取律师列表失败:', error)
      ElMessage.error('获取律师列表失败')
    }
  }

  // 处理查询
  const handleSearch = () => {
    queryForm.page = 1
    getCaseList()
  }

  // 处理重置
  const handleReset = () => {
    // 重置所有搜索表单字段
    queryForm.keywords = ''
    queryForm.main_lawyer = ''
    queryForm.manager = ''
    queryForm.session_lawyer = ''
    queryForm.status = ''
    queryForm.date_range = []
    queryForm.session_time_range = []
    queryForm.suspend_status = ''
    queryForm.page = 1
    // 清除表单验证状态
    queryFormRef.value?.clearValidate()
    getCaseList()
  }

  // 处理页码改变
  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getCaseList()
  }

  // 处理每页条数改变
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1
    getCaseList()
  }

  // 处理查看案件
  const handleView = (row: LawCase) => {
    currentCase.value = row
    drawerVisible.value = true
    loadCaseDetail(row.id)
  }

  // 加载案件详情
  const isLoadingDetail = ref(false)
  const loadCaseDetail = async (caseId: number) => {
    // 防止重复请求
    if (isLoadingDetail.value) {
      return
    }

    try {
      isLoadingDetail.value = true
      // 获取案件详情
      const detailRes: any = await request({
        url: `/api/lawcase/cases/view?id=${caseId}`,
        method: 'get',
      })

      if (detailRes.code === 0 && detailRes.data) {
        // 确保时间字段格式正确
        const caseData = detailRes.data
        // 规范化时间字段 - 确保时间戳转换正确
        if (caseData.create_time) {
          caseData.create_time = normalizeTimestamp(caseData.create_time)
        }
        if (caseData.update_time) {
          caseData.update_time = normalizeTimestamp(caseData.update_time)
        }
        // 案件的session_time是时间戳，需要规范化处理
        if (caseData.session_time) {
          caseData.session_time = normalizeTimestamp(caseData.session_time)
        }

        // 设置抽屉可见
        drawerVisible.value = true

        // 确保manager字段存在且正确传递
        if (caseData.manager === undefined || caseData.manager === null) {
          caseData.manager = '' // 设置默认空值，避免编辑表单中出现undefined
        }

        currentCase.value = caseData

        // 构建基本请求数组
        const requests = [
          lawcaseStore.getPartyListAction({ case_id: caseId, page: 1, limit: 100 }),
          lawcaseStore.getProgressListAction({ case_id: caseId, page: 1, limit: 100 }),
          lawcaseStore.getCaseDocListAction({ case_id: caseId, page: 1, limit: 100 }),
        ]

        // 等待所有请求完成
        const results = await Promise.allSettled(requests)

        // 处理当事人列表结果
        const partiesRes = results[0]
        if (partiesRes.status === 'fulfilled' && partiesRes.value && partiesRes.value.code === 0) {
          // 确保正确处理数据结构
          const partiesData = partiesRes.value.data
          // 检查是否是分页对象，如果是则取list字段
          if (
            partiesData &&
            typeof partiesData === 'object' &&
            Array.isArray((partiesData as any).list)
          ) {
            partyList.value = (partiesData as any).list.map((party: any) => ({
              ...party,
              // 确保partyName属性正确设置
              partyName: party.partyName || party.name || party.party_name || '未知当事人',
              party_name: party.partyName || party.name || party.party_name || '未知当事人',
              // 确保partyType属性正确设置
              partyType: party.partyType || party.type || party.party_type || 0,
              party_type: party.partyType || party.type || party.party_type || 0,
              // 确保其他必要属性存在
              is_client_text: party.is_client_text || '',
              relationship_text: party.relationship_text || '',
              idNumber: party.idNumber || party.id_number || '',
              contactPhone: party.contactPhone || party.phone || '',
              contactPerson: party.contactPerson || party.contact || '',
            })) as ConvertedParty[]
          } else if (Array.isArray(partiesData)) {
            // 保持原有的数组处理逻辑，兼容旧版本API
            partyList.value = partiesData.map((party: any) => ({
              ...party,
              // 确保partyName属性正确设置
              partyName: party.partyName || party.name || party.party_name || '未知当事人',
              party_name: party.partyName || party.name || party.party_name || '未知当事人',
              // 确保partyType属性正确设置
              partyType: party.partyType || party.type || party.party_type || 0,
              party_type: party.partyType || party.type || party.party_type || 0,
              // 确保其他必要属性存在
              is_client_text: party.is_client_text || '',
              relationship_text: party.relationship_text || '',
              idNumber: party.idNumber || party.id_number || '',
              contactPhone: party.contactPhone || party.phone || '',
              contactPerson: party.contactPerson || party.contact || '',
            })) as ConvertedParty[]
          } else {
            partyList.value = []
          }
        }

        // 处理进度列表结果
        const progressRes = results[1]
        if (
          progressRes.status === 'fulfilled' &&
          progressRes.value &&
          progressRes.value.code === 0
        ) {
          // 确保 data 是数组，然后进行类型转换
          const progressData = progressRes.value.data
          // 检查是否是分页对象，如果是则取list字段
          if (
            progressData &&
            typeof progressData === 'object' &&
            Array.isArray((progressData as any).list)
          ) {
            progressList.value = (progressData as any).list as unknown as Progress[]
          } else if (Array.isArray(progressData)) {
            // 保持原有的数组处理逻辑，兼容旧版本API
            progressList.value = progressData as unknown as Progress[]
          } else {
            progressList.value = []
          }
        }
      } else {
        const errorMsg = detailRes.msg || '获取案件详情失败'
        ElMessage.error(errorMsg)
      }
    } catch (error) {
      ElMessage.error(`加载案件详情失败: ${error instanceof Error ? error.message : String(error)}`)
    } finally {
      // 请求完成后重置加载状态
      isLoadingDetail.value = false
    }
  }

  // 处理新增案件
  const handleAdd = () => {
    isEdit.value = false
    currentEditCase.value = null
    addDrawerVisible.value = true
  }

  // 处理编辑案件
  const handleEdit = (row: LawCase) => {
    isEdit.value = true
    // 保存当前编辑的案件数据，确保数据格式正确
    // 创建一个深拷贝，避免引用问题
    currentEditCase.value = JSON.parse(JSON.stringify(row))

    // 确保接案日期格式正确，用于编辑表单显示
    if (
      currentEditCase.value &&
      currentEditCase.value.entrust_date &&
      typeof currentEditCase.value.entrust_date === 'number'
    ) {
      // 如果是时间戳，转换为日期字符串
      currentEditCase.value.entrust_date = formatDate(
        currentEditCase.value.entrust_date,
        'YYYY-MM-DD'
      )
    }

    // 从接口返回的数据来看，管家信息存储在secondary_lawyer和secondary_lawyer_name字段中
    // 我们需要将这些值映射到表单所需的manager和manager_name字段上
    if (
      currentEditCase.value &&
      currentEditCase.value.secondary_lawyer &&
      !currentEditCase.value.manager
    ) {
      currentEditCase.value.manager = Number(currentEditCase.value.secondary_lawyer)
    }

    if (
      currentEditCase.value &&
      currentEditCase.value.secondary_lawyer_name &&
      !currentEditCase.value.manager_name
    ) {
      currentEditCase.value.manager_name = currentEditCase.value.secondary_lawyer_name
    }

    // 确保管家字段存在且格式正确
    if (
      currentEditCase.value &&
      (currentEditCase.value.manager === undefined || currentEditCase.value.manager === null)
    ) {
      currentEditCase.value.manager = ''
    } else if (currentEditCase.value && typeof currentEditCase.value.manager === 'number') {
      // 确保manager是数字类型，不是字符串
      currentEditCase.value.manager = Number(currentEditCase.value.manager)
    }

    // 确保管家名称字段存在且格式正确，避免在CaseEditForm中出现undefined
    if (
      currentEditCase.value &&
      (currentEditCase.value.manager_name === undefined ||
        currentEditCase.value.manager_name === null ||
        currentEditCase.value.manager_name === '')
    ) {
      // 如果没有管家名称，尝试从律师列表中查找
      if (
        currentEditCase.value &&
        lawyerOptions.value &&
        lawyerOptions.value.length > 0 &&
        currentEditCase.value.manager
      ) {
        const editCase = currentEditCase.value
        const foundLawyer = lawyerOptions.value.find(option => option.id === editCase.manager)
        if (foundLawyer) {
          editCase.manager_name = foundLawyer.lawyer_name
        } else {
          // 如果找不到匹配的律师，设置默认名称
          editCase.manager_name = `管家${editCase.manager}`
        }
      } else if (currentEditCase.value) {
        currentEditCase.value.manager_name = ''
      }
    }

    addDrawerVisible.value = true
  }

  // 处理案件挂起/取消挂起
  const handleSuspend = (row: LawCase) => {
    const isCurrentlySuspended = row.is_suspended === 1
    const actionText = isCurrentlySuspended ? '取消挂起' : '挂起'
    const confirmText = `确定要${actionText}该案件吗？`

    ElMessageBox.confirm(confirmText, `确认${actionText}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: any = await request({
            url: `/api/lawcase/cases/suspend`,
            method: 'post',
            data: {
              id: row.id,
              status: isCurrentlySuspended ? 0 : 1,
            },
          })

          if (response.code === 0) {
            ElMessage.success(`${actionText}成功`)
            getCaseList()
          } else {
            ElMessage.error(response.msg || `${actionText}失败`)
          }
        } catch (error) {
          ElMessage.error(`${actionText}失败`)
        }
      })
      .catch(() => {
        // 用户取消操作
      })
  }

  // 处理删除案件
  const handleDelete = (row: LawCase) => {
    ElMessageBox.confirm('确定要删除该案件吗？此操作不可恢复', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: any = await request({
            url: `/api/lawcase/cases/del?id=${row.id}`,
            method: 'delete',
          })

          if (response.code === 0) {
            ElMessage.success('删除成功')
            getCaseList()
          } else {
            ElMessage.error(response.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 处理保存案件
  const caseEditFormRef = ref()
  const handleSave = () => {
    // 调用CaseEditForm组件的handleSubmit方法
    if (caseEditFormRef.value && typeof caseEditFormRef.value.handleSubmit === 'function') {
      caseEditFormRef.value.handleSubmit()
    } else {
      console.error('CaseEditForm组件或handleSubmit方法不存在')
    }
  }

  // 处理CaseEditForm提交成功的回调
  const handleCaseFormSuccess = () => {
    ElMessage.success(isEdit.value ? '案件更新成功' : '案件创建成功')
    addDrawerVisible.value = false
    // 重新获取案件列表
    getCaseList()
  }

  // 处理添加当事人
  const handleAddParty = () => {
    // 显示当事人选择器对话框
    partySelectorVisible.value = true
  }

  // 处理编辑当事人
  const handleEditParty = (row: Party) => {
    console.log('编辑当事人数据:', row)
    // 填充编辑表单数据，确保字段映射正确，符合EditPartyData接口
    editPartyForm.value = {
      id: row.id,
      case_id: row.case_id,
      party_id: row.party_id,
      name: row.partyName || row.name || '',
      party_name: row.partyName || row.name || '',
      party_type: row.partyType === 2 || row.party_type_name === '企业' ? 2 : 1,
      id_number: row.idNumber || row.id_number || '',
      contact: row.contactPerson || row.contact || '',
      mobile: row.contactPhone || row.phone || '',
      address: row.address || '',
      email: row.email || '',
      remark: row.remark || '',
      is_client:
        row.is_client ||
        (row.is_client_text === '委托人' ? 1 : row.is_client_text === '对方当事人' ? 2 : 3),
      relationship:
        row.relationship ||
        (row.relationship_text === '原告'
          ? 1
          : row.relationship_text === '被告'
            ? 2
            : row.relationship_text === '第三人'
              ? 3
              : row.relationship_text === '上诉人'
                ? 4
                : row.relationship_text === '被上诉人'
                  ? 5
                  : row.relationship_text === '再审申请人'
                    ? 6
                    : row.relationship_text === '再审被申请人'
                      ? 7
                      : row.relationship_text === '申请执行人'
                        ? 8
                        : row.relationship_text === '被申请执行人'
                          ? 9
                          : 1),
    }

    console.log('设置编辑表单数据:', editPartyForm.value)

    // 强制触发响应式更新，确保数据正确传递给子组件
    editPartyForm.value = { ...editPartyForm.value }

    // 显示编辑当事人对话框
    isEditParty.value = true
    partyDialogVisible.value = true
  }

  // 处理当事人表单提交成功
  const handlePartyFormSuccess = () => {
    ElMessage.success(isEditParty.value ? '当事人更新成功' : '当事人添加成功')
    // 重新获取案件详情，刷新当事人卡片
    if (currentCase.value && currentCase.value.id) {
      loadCaseDetail(currentCase.value.id)
    }
  }

  // 处理当事人对话框关闭
  const handlePartyDialogClose = () => {
    partyDialogVisible.value = false
    // 重置编辑状态
    isEditParty.value = false
  }

  // 处理移除当事人
  const handleRemoveParty = (row: Party) => {
    ElMessageBox.confirm('确定要移除该当事人吗？', '确认移除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          // 检查row对象和id的存在性
          if (!row || !row.id) {
            ElMessage.error('当事人信息无效')
            return
          }

          // 调用移除当事人的API接口
          const response: any = await request({
            url: '/api/lawcase/parties/unlink',
            method: 'post',
            data: { id: row.id },
          })

          // 处理响应
          if (response && response.code === 0) {
            ElMessage.success('当事人移除成功')
            // 重新加载案件详情，刷新当事人列表
            if (currentCase.value && currentCase.value.id) {
              loadCaseDetail(currentCase.value.id)
            }
          } else {
            ElMessage.error(response?.msg || '当事人移除失败')
          }
        } catch (error) {
          // 避免在用户取消操作时显示错误信息
          if (!(error instanceof Error && error.message === 'cancel')) {
            ElMessage.error(
              `移除当事人失败: ${error instanceof Error ? error.message : String(error)}`
            )
          }
        }
      })
      .catch(() => {
        // 用户取消移除
      })
  }

  // 处理添加进度
  const handleAddProgress = () => {
    // 重置表单并显示对话框
    if (
      progressFormComponentRef.value &&
      typeof progressFormComponentRef.value.resetForm === 'function'
    ) {
      progressFormComponentRef.value.resetForm()
    }
    progressDialogVisible.value = true
  }

  // 处理提交进度
  const handleSubmitProgress = () => {
    if (
      progressFormComponentRef.value &&
      typeof progressFormComponentRef.value.submitForm === 'function'
    ) {
      progressFormComponentRef.value.submitForm()
    }
  }

  // 处理进度提交成功
  const handleProgressSuccess = () => {
    progressDialogVisible.value = false
    if (currentCase.value && currentCase.value.id) {
      loadCaseDetail(currentCase.value.id)
    }
  }

  // 处理编辑案件
  const handleEditCase = () => {
    if (currentCase.value) {
      handleEdit(currentCase.value)
    }
  }

  // 处理刷新案件
  const handleRefreshCase = () => {
    if (currentCase.value && currentCase.value.id) {
      loadCaseDetail(currentCase.value.id)
    }
  }

  // 处理当事人选择成功
  const handlePartySuccess = () => {
    // 当事人选择成功后刷新案件详情
    if (currentCase.value && currentCase.value.id) {
      loadCaseDetail(currentCase.value.id)
    }
  }

  // 关闭抽屉前的处理
  const handleAddDrawerClose = () => {
    return ElMessageBox.confirm('确定要关闭吗？未保存的数据将会丢失')
      .then(() => {
        return true
      })
      .catch(() => {
        // 用户取消关闭
        return false
      })
  }

  // normalizeTimestamp函数已移至文件顶部

  // 格式化时间
  const formatTime = (time: number | string, format: 'date' | 'datetime' | 'time' = 'date') => {
    try {
      const normalizedTime = normalizeTimestamp(time)
      let formatStr = 'YYYY-MM-DD'

      switch (format) {
        case 'datetime':
          formatStr = 'YYYY-MM-DD HH:mm:ss'
          break
        case 'time':
          formatStr = 'YYYY-MM-DD HH:mm:ss' // 修改为显示完整的日期时间格式
          break
      }

      return formatDate(normalizedTime, formatStr)
    } catch (error) {
      return ''
    }
  }

  // 进度表单组件引用
  const progressFormComponentRef = ref()

  // 判断是否为紧急案件（开庭时间在3天内）
  const isUrgentCase = (row: LawCase) => {
    if (!row.session_time) return false

    try {
      // 确保正确处理秒级时间戳
      const timeValue =
        typeof row.session_time === 'string' ? parseInt(row.session_time) : row.session_time

      // 检查是否是秒级时间戳（10位左右），如果是则转换为毫秒级
      let timestamp = timeValue
      if (typeof timestamp === 'number' && timestamp.toString().length <= 10) {
        timestamp = timestamp * 1000 // 秒级时间戳转换为毫秒级
      }

      const sessionDate = new Date(timestamp)

      // 检查是否是有效日期
      if (isNaN(sessionDate.getTime())) {
        return false
      }

      const now = new Date()
      const diffDays = Math.ceil((sessionDate.getTime() - now.getTime()) / (1000 * 3600 * 24))

      return diffDays > 0 && diffDays <= 3
    } catch (error) {
      return false
    }
  }

  // 单元格样式
  const cellStyle = ({ row }: { row: any }) => {
    // 如果是紧急案件（开庭时间在3天内），添加特殊样式
    if (isUrgentCase(row)) {
      return {
        color: 'red',
        fontWeight: 'bold',
      }
    }
    return {}
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getCaseList()
    getLawyerList()
  })
</script>

<style scoped>
  .lawcase-container {
    padding: 16px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .lawcase-header {
    margin-bottom: 16px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .search-input {
    width: 200px;
  }

  .search-select {
    width: 200px;
  }

  .search-buttons {
    margin-left: auto;
  }

  .lawcase-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  .lawcase-table {
    flex: 1;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .case-form {
    max-height: 70vh;
    overflow-y: auto;
    padding-right: 10px;
  }

  .status-select,
  .lawyer-select,
  .date-picker,
  .datetime-picker {
    width: 100%;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .cell-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
